﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media.Animation;

namespace Gmantis.Controls
{
    [TemplatePart(Name = "VerticalTemplate", Type = typeof(FrameworkElement)), TemplateVisualState(Name = "Disabled", GroupName = "CommonStates"), TemplateVisualState(Name = "MouseOver", GroupName = "CommonStates"), TemplatePart(Name = "HorizontalTemplate", Type = typeof(FrameworkElement)), TemplateVisualState(Name = "Normal", GroupName = "CommonStates")]
    public class Separator : Control
    {
        // Fields
        internal FrameworkElement _elementHorizontalTemplate;
        internal FrameworkElement _elementVerticalTemplate;
        private bool _throwIsMouseOverChanged;        
        internal static readonly DependencyProperty ForceMouseOverProperty = DependencyProperty.Register("ForceMouseOver", typeof(bool), typeof(Separator), new PropertyMetadata(new PropertyChangedCallback(Separator.OnForceMouseOverPropertyChanged)));
        internal const string HorizontalTemplateElementName = "HorizontalTemplate";
        public static readonly DependencyProperty IsMouseOverProperty = DependencyProperty.Register("IsMouseOver", typeof(bool), typeof(Separator), new PropertyMetadata(new PropertyChangedCallback(Separator.OnIsMouseOverPropertyChanged)));
        public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register("Orientation", typeof(Orientation), typeof(Separator), new PropertyMetadata(Orientation.Horizontal));
        internal const string VerticalTemplateElementName = "VerticalTemplate";

        // Events
        public event EventHandler<PropertyChangedEventArgs<bool>> IsMouseOverChanged;

        // Methods
        public Separator()
        {
            RoutedEventHandler handler = null;
            DependencyPropertyChangedEventHandler handler2 = null;
            this._throwIsMouseOverChanged = true;
            base.DefaultStyleKey = typeof(Separator);
            if (handler == null)
            {
                handler = (param0, param1) => this.ChangeVisualStateCommon(false);
            }
            base.Loaded += handler;
            if (handler2 == null)
            {
                handler2 = (s, a) => this.ChangeVisualStateCommon(true);
            }
            base.IsEnabledChanged += handler2;
            base.MouseEnter += new MouseEventHandler(this.Control_MouseEnter);
            base.MouseLeave += new MouseEventHandler(this.Control_MouseLeave);
            this.SetCustomDefaultValues();
        }

        private void Control_MouseEnter(object sender, MouseEventArgs e)
        {
            if (InputEventArgs.GetPointerType(e) == PointerDeviceType.Mouse)
            {
                this.IsMouseOver = true;
            }
        }

        private void Control_MouseLeave(object sender, MouseEventArgs e)
        {
            if (InputEventArgs.GetPointerType(e) == PointerDeviceType.Mouse)
            {
                this.IsMouseOver = false;
            }
        }

        protected void ChangeVisualStateCommon(bool useTransitions)
        {
            if (!base.IsEnabled)
            {
                VisualStateHelper.GoToState(this, "Disabled", useTransitions);
            }
            if (base.IsEnabled)
            {
                VisualStateHelper.GoToState(this, "MouseOver", useTransitions);
            }
            if ((base.IsEnabled && !this.IsMouseOver) && !this.ForceMouseOver)
            {
                VisualStateHelper.GoToState(this, "Normal", useTransitions);
            }
        }

        private T GetTemplateChild<T>(string childName, bool required, ref string errors) where T : class
        {
            DependencyObject templateChild = base.GetTemplateChild(childName);
            ApplyTemplateHelper.VerifyTemplateChild(typeof(T), "template part", childName, templateChild, required, ref errors);
            return (templateChild as T);
        }

        private static Storyboard GetTemplateChildResource(FrameworkElement root, string resourceName, bool required, ref string errors)
        {
            return GetTemplateChildResource<Storyboard>(root, resourceName, required, ref errors);
        }

        private static T GetTemplateChildResource<T>(FrameworkElement root, string resourceName, bool required, ref string errors) where T : class
        {
            object child = root.Resources[resourceName];
            ApplyTemplateHelper.VerifyTemplateChild(typeof(T), "resource", resourceName, child, required, ref errors);
            return (child as T);
        }

        private void InitializeHorizontalTemplatePart()
        {
            Binding binding = new Binding
            {
                Converter = CustomConverter.Create((value, type, parameter, culture) => (((Orientation)value) == Orientation.Horizontal) ? Visibility.Visible : Visibility.Collapsed)
            };
            this._elementHorizontalTemplate.SetBinding(UIElement.VisibilityProperty, binding.From<Separator>(this, x => x.Orientation));
        }

        private void InitializeVerticalTemplatePart()
        {
            Binding binding = new Binding
            {
                Converter = CustomConverter.Create((value, type, parameter, culture) => (((Orientation)value) == Orientation.Vertical) ? Visibility.Visible : Visibility.Collapsed)
            };
            this._elementVerticalTemplate.SetBinding(UIElement.VisibilityProperty, binding.From<Separator>(this, x => x.Orientation));
        }

        public override void OnApplyTemplate()
        {
            string errors = string.Empty;
            base.OnApplyTemplate();
            this._elementVerticalTemplate = this.GetTemplateChild<FrameworkElement>("VerticalTemplate", false, ref errors);
            if (this._elementVerticalTemplate != null)
            {
                this.InitializeVerticalTemplatePart();
            }
            this._elementHorizontalTemplate = this.GetTemplateChild<FrameworkElement>("HorizontalTemplate", false, ref errors);
            if (this._elementHorizontalTemplate != null)
            {
                this.InitializeHorizontalTemplatePart();
            }
            if (!string.IsNullOrEmpty(errors))
            {
                if ((base.Template != null) && !PlatformIndependent.IsInDesignMode(this))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Template cannot be applied to Separator.\nDetails: {0}", new object[] { errors }));
                }
            }
            else
            {
                this.ChangeVisualStateCommon(false);
            }
        }

        private static void OnForceMouseOverPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as Separator).ChangeVisualStateCommon(true);
        }

        private static void OnIsMouseOverPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Separator sender = d as Separator;
            if ((sender.IsMouseOverChanged != null) && sender._throwIsMouseOverChanged)
            {
                PropertyChangedEventArgs<bool> args = new PropertyChangedEventArgs<bool>
                {
                    OldValue = (bool)e.OldValue,
                    NewValue = (bool)e.NewValue
                };
                sender.IsMouseOverChanged(sender, args);
            }
            sender.ChangeVisualStateCommon(true);
        }

        private void SetCustomDefaultValues()
        {
            base.IsTabStop = false;
        }

        // Properties
        internal bool ForceMouseOver
        {
            get { return (bool)GetValue(ForceMouseOverProperty); }
            set { SetValue(ForceMouseOverProperty, value); }
        }

        public bool IsMouseOver
        {
            get { return (bool)GetValue(IsMouseOverProperty); }
            set { SetValue(IsMouseOverProperty, value); }
        }

        public Orientation Orientation
        {
            get { return (Orientation)GetValue(OrientationProperty); }
            set { SetValue(OrientationProperty, value); }
        }
    }
}
